import { uploadBulk } from "../複数の画像ファイルをGyazoにuploadするscript/upload.ts";
import {
  basename,
  extname,
  resolve,
} from "https://deno.land/std@0.122.0/path/mod.ts";
import { readZip } from "https://deno.land/x/jszip@0.11.0/mod.ts";

// directory内の全てのzipを読み込む
const dir = resolve(Deno.cwd(), Deno.args[0]);
console.log(dir);
const name = basename(dir);
if (!(await Deno.stat(dir)).isDirectory) {
  throw Error(`"${name}" is not a directory. Specify a directory path.`);
}

for await (const { name: fileName } of Deno.readDir(dir)) {
  const path = resolve(dir, fileName);
  if (extname(path) !== ".zip") continue;
  
  const zip = await readZip(path);
  console.log(`Open ${fileName}`);
  
  const files: File[] = [];
  for (const file of zip) {
    const blob = await file.async("blob");
    files.push(new File([blob], file.name, {
      lastModified: file.date.getTime(),
    }));
    console.log(`Extract ${file.name}`);
  }
  files.sort((a, b) => parseInt(a.name) - parseInt(b.name));
  
  const [year, date] = fileName.match(/(\d{4})-(\d{2})/)?.slice?.(1) ?? ["", ""];
  const title = `『山と渓谷 ${parseInt(year)}年${parseInt(date)}月号』`;
  console.log(`Upload ${title}`);
  
  const errors = [] as number[];
  let counter = 0;
  const URLs = [] as string[];
  for await (const result of uploadBulk(
    files,
    {
      title,
      noIndex: true,
      accessToken: Deno.args[1],
    },
  )) {
    counter++;
    if (!result.success) {
      if (!(result.reason instanceof Error)) throw result.reason;
      console.error(`[${counter}/${files.length}] `, result.reason);
      errors.push(counter);
    } else {
      const { permalink_url, name, index } = result.value;
      URLs[index] = permalink_url;
      console.log(`[${counter}/${files.length}] ${name} ${permalink_url}`);
    }
  }
  if (errors.length > 0) console.log(errors);
  // .zipを削ってファイル名を組み立てる
  await Deno.writeTextFile(resolve(dir, `./${fileName.slice(0, -extname(fileName).length)}-gyazo.json`), JSON.stringify(URLs));
}